Skip to content

fix(@angular/cli): validate path options against MCP roots in host execution - #34773

Open
JeanMeche wants to merge 1 commit into
angular:mainfrom
JeanMeche:fix/mcp-run-target-path-validation
Open

JeanMeche wants to merge 1 commit into
angular:mainfrom
JeanMeche:fix/mcp-run-target-path-validation

Conversation

@JeanMeche

@JeanMeche JeanMeche commented Nov 22, 2026 •

Copy link
Copy Markdown
Member

PR Checklist

Please check to confirm your PR fulfills the following requirements:

PR Type

What kind of change does this PR introduce?

  • Bugfix
  • Feature
  • Code style update (formatting, local variables)
  • Refactoring (no functional changes, no api changes)
  • Build related changes
  • CI related changes
  • Documentation content changes
  • Other... Please describe:

What is the current behavior?

In the MCP server (ng mcp), createRootRestrictedHost only checked effectiveCwd before calling executeNgCommand / startNgProcess. Option flags forwarded from run_target via serializeOptions (such as --output-path, --out-file, --output-file, --ts-config, --runner-config, --karma-config, etc.) were passed directly to the spawned ng command without verifying that their paths remained within the allowed MCP roots.

For example, invoking run_target with {"target": "build", "options": {"output-path": "/path/outside/root"}} allowed the spawned builder to escape the root-restricted boundary, recursively clean the target directory via deleteOutputDir (since deleteOutputDir only rejects exact equality with the workspace root), and write build outputs outside allowed MCP roots.

Issue Number: b/587904432

What is the new behavior?

  • createRootRestrictedHost (packages/angular/cli/src/commands/mcp/host.ts):
    • Validates path-bearing, glob-based, and output-directory CLI flags passed to executeNgCommand and startNgProcess against the active allowed MCP roots (supporting both --flag=value and separate --flag value forms, camelCase/kebab-case/snake_case keys, dot-notation, negation forms with =, --runner-args, and passthrough args after --).
    • Rejects output directory flags (--output-path, --output-dir, etc.) when the resolved target is outside allowed roots or is equal to / an ancestor of the effective workspace directory or any allowed root.
    • Validates compound relative output flags (--out-file, --resources-output-path) against both cwd and any supplied output directory, regardless of argument order.
    • Leaves non-filesystem flags intact (e.g., --base-href, --deploy-url, --serve-path, --route, --routes, --filter, --delete-output-path, --output-hashing, --output-mode, and boolean values for union options such as index, server, serviceWorker, and runnerConfig).
    • Hardens real-path resolution in createRootRestrictedHost to follow dangling symlinks, handle intermediate symlinks before .. segments, and check exact path separator boundaries (.. directory prefixes such as ..hidden.txt inside a root are allowed).
  • serializeOptions (packages/angular/cli/src/commands/mcp/tools/run-target/options-serializer.ts):
    • Tightens option key validation to require a leading alphanumeric character (^[a-zA-Z0-9][a-zA-Z0-9-_]*$).
    • Rejects null bytes (\0) in string option values.
    • Normalizes excludeKeys comparison so case/separator variants cannot bypass excluded keys (e.g., watch).
  • run_target strategies (build-target-strategy.ts, generic-target-strategy.ts, unit-test-strategy.ts):
    • Re-throws non-CommandError exceptions (such as root access-denied errors from createRootRestrictedHost) instead of catching them as failed command execution logs.

Does this PR introduce a breaking change?

  • Yes
  • No

Other information

deleteOutputDir in @angular/build was intentionally left unchanged so direct ng build CLI invocations with explicit external absolute output paths (e.g. /tmp/...) continue to work as expected; confinement is enforced at the MCP host boundary.

…ecution

Ensure `createRootRestrictedHost` validates path-bearing CLI flags passed to `executeNgCommand` and `startNgProcess` against the active allowed MCP roots, instead of checking only the effective `cwd`.

Previously, the `run_target` MCP tool forwarded client-supplied options directly to the spawned `ng` process (for example, `--output-path=/outside/root`). Because builders such as `@angular/build:application` resolve `outputPath` via `path.resolve(workspaceRoot, outputPath)` and recursively clear it via `deleteOutputDir`, an out-of-root path escaped MCP root confinement.

Changes:
- Validate path-bearing, glob-based, and output-directory CLI flags (both `--flag=value` and `--flag value`, camelCase/kebab-case/snake_case, negation, dot-notation, `--runner-args`, and passthrough args) in `createRootRestrictedHost.executeNgCommand` and `startNgProcess`.
- Reject output directory flags (`--output-path`, `--output-dir`, etc.) that resolve outside allowed roots or equal/are an ancestor of the workspace directory or any allowed root.
- Preserve non-filesystem flags such as `--base-href`, `--deploy-url`, `--serve-path`, `--route`, `--filter`, and boolean literals on boolean-or-path options.
- Harden canonical path resolution in `createRootRestrictedHost` to resolve dangling symlinks, handle intermediate symlinks prior to `..` segments, and check exact path separator boundaries.
- Tighten `serializeOptions` key validation to require a leading alphanumeric character, reject null bytes in string option values, and normalize `excludeKeys` comparison.
- Propagate non-`CommandError` rejections (such as root access-denied errors) from the `run_target` target strategies instead of swallowing them as command failures.
@JeanMeche
JeanMeche marked this pull request as ready for review November 23, 2026 14:37
@JeanMeche
JeanMeche requested a review from clydin November 23, 2026 14:37

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces robust path validation and confinement checks for Angular CLI commands run via the MCP host. It adds comprehensive validation of command-line arguments, resolving symlinks and verifying that output paths, exact paths, and glob patterns remain strictly within allowed root directories. Additionally, error handling is updated to propagate command errors, and options serialization is hardened against null bytes and invalid keys. The review feedback highlights two important issues: a potential security bypass in runner-args parsing when multiple space-separated arguments are passed as a single string, and a regex restriction in serializeOptions that incorrectly blocks valid dot-notation options.

@alan-agius4 alan-agius4 added target: patch This PR is targeted for the next patch release action: review The PR is still awaiting reviews from at least one requested reviewer labels Nov 24, 2026

@alan-agius4 alan-agius4 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The symlink/dangling-symlink resolution and CommandError propagation look solid, but there are a few confinement bypasses to tighten before merging (see inline comments).

One extra note outside the diff: since serializeOptions now normalizes excludeKeys case-insensitively for watch, GenericTargetStrategy (generic-target-strategy.ts:34) still checks exact input.options?.['watch'] === true, so { WATCH: true } can still bypass the watch-mode guard there.

/**
* Normalized option names that accept filesystem paths.
*/
const EXACT_PATH_OPTIONS = new Set([

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

reporters and coverageReporters (unit-test builder) should also be listed here — reporters accepts a file path to a custom reporter (which Vitest loads and executes), so passing --reporters=/outside/evil.mjs currently bypasses root confinement. Built-in names like default or json resolve under cwd and remain allowed.

throw new Error(`Access denied: ${label} contains path traversal sequences.`);
}

if (normalized.startsWith('{')) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This only checks brace expansion when the pattern starts with {. A pattern like ./{link-out,src}/*.spec.ts or src/{/outside,a}/*.spec.ts skips the brace check because basePath is ./ / src/ and wildcardTail contains no ...

Also, pattern.startsWith('!') above only strips a single leading !, and createRootRestrictedHost.glob() below should reuse validateGlobOptionValue so it isn't left vulnerable to {/outside,src}/* (and stays consistent with allowing ..hidden.txt).

continue;
}

const withoutPrefix = arg.startsWith('--') ? arg.slice(2) : arg.slice(1);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A few argument-parsing edge cases here:

  • Yargs has short-option-groups enabled by default, so an attached short flag like -o/outside/path gets parsed here as rawKey = 'o/outside/path' ('none') and bypasses validation.
  • Inside --runner-args / --, Vitest also accepts -c (--config) and -r (--root), whereas only -o is classified as a path.
  • In the separate-arg branch below (!args[i + 1].startsWith('-')), a path starting with - (e.g. --ts-config -x/../../outside/tsconfig.json via direct executeNgCommand or split --runner-args) leaves value as undefined and skips validation.


if (kind === 'runner-args') {
if (value !== undefined) {
nestedRunnerArgs.push(value);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re: the bot comment on splitting by \s+ — don't split unconditionally, since that would break legitimate paths containing spaces inside an allowed root (and @angular/build:unit-test passes runnerArgs elements directly to Vitest's parseCLI with an explicit allowlist rather than shell-splitting). If we want defense-in-depth for third-party builders that might split --runner-args, we should validate the raw value and only reject/re-check when embedded whitespace-delimited flags (e.g. /\s--?[a-zA-Z]/) are present.

validateGlobOptionValue(roots, flag, value, cwd, realCwd);
} else if (kind === 'output-relative') {
validateOptionPathValue(roots, flag, value, cwd, realCwd);
outputRelativeChecks.push({ flag, value });

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Two gaps with output-relative options (--out-file, --resources-output-path, --output-path.browser/.server/.media):

  • They are only checked against CLI-supplied outputDirs, not outputPath from angular.json. In a monorepo (cwd at root/apps/web, angular.json setting outputPath: "../../dist"), passing only --out-file=../escape.xlf passes the cwd check (root/apps/escape.xlf) but writes outside root when resolved against outputPath.
  • They don't run assertNotWorkspaceOrRootAncestor, so --output-path=dist/app --output-path.browser=../.. resolves directly to the workspace root and passes.

Output-relative options shouldn't be absolute or traverse above their base directory with .. — rejecting that directly would cover both cases.


if (!/^[a-zA-Z0-9-_]+$/.test(key)) {
for (const [key, value] of Object.entries(options)) {
if (!/^[a-zA-Z0-9][a-zA-Z0-9-_]*$/.test(key)) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Keep this regex without . (contrary to the bot suggestion). Angular CLI disables 'dot-notation' in Yargs and ignores nested object properties in parseJsonSchemaToOptions, so dot-notation keys aren't accepted on the CLI anyway (and Vitest options like --sequence.shuffle are passed in runner-args values, not option keys).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

action: review The PR is still awaiting reviews from at least one requested reviewer area: @angular/cli target: patch This PR is targeted for the next patch release

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants